package sz.szsmk.citizencard.ui.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.chenenyu.router.annotation.Route;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.dialog.TwoButtonDialog;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.QueryUserCardRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryUserCardResponse;
import sz.szsmk.citizencard.model.network.bean.response.YXCRes;
import sz.szsmk.citizencard.mvp.BasePresenter;
import sz.szsmk.citizencard.mvp.IBindCitizenCardMvpView;
import sz.szsmk.citizencard.mvp.presenter.BindCitizenCardPresenter;
import sz.szsmk.citizencard.ui.adapter.CardViewFunAdapter;
import sz.szsmk.citizencard.ui.adapter.CitizenCardvpAdatper;
import sz.szsmk.citizencard.ui.adapter.ContentAdapter;
import sz.szsmk.citizencard.ui.dzsmkavtivity.AppBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidDeviceInfo;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpThirdView;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.widget.BlurringView;
import sz.szsmk.citizencard.widget.ZoomIndicator;

import static sz.szsmk.citizencard.util.StringUtils.doubleToString;
import static sz.szsmk.citizencard.util.StringUtils.formatMoney;


/**
 * author : hyt
 * date : 2019/10/10
 * description : 卡片详情页面
 */
@Route("CitizenCardActivity")
public class CitizenCardActivity extends AppBaseActivity implements IBindCitizenCardMvpView {

    private String origin;
    private String access_token;

    public static final int CHANGE_NICKNAME_REQUEST_CODE = 10000;

    @Inject
    BindCitizenCardPresenter presenter;


    ViewPager vp_cardList;

    ZoomIndicator zi_cardListIndicator;

    private CitizenCardvpAdatper cardAdapter;

    RecyclerView rv_recyclerview;

    ContentAdapter adapter ;

    //当前选中的 卡
    int currentPosition = 0;
    private String errormsg;
    private Integer money;

    @Override
    protected void initSystemBar() {
        ImmersionBar.with(this).init();
    }

    @Override
    protected CharSequence getTopTitle() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getComponent().inject(this);
        setContentView(R.layout.routine_card_activity2);

        vp_cardList = findViewById(R.id.vp_cardList);

        zi_cardListIndicator = findViewById(R.id.zi_cardListIndicator);

        rv_recyclerview =  findViewById(R.id.rv_recyclerview);


        findViewById(R.id.tv_transactionRecord).setOnClickListener(this::onClick);
        findViewById(R.id.back).setOnClickListener(this::onClick);



        showLoadingDialog();
        init();
        initViewPager();

//        QueryUserCardRes data = (QueryUserCardRes) getIntent().getSerializableExtra("citizenCardData");
//        if (data != null) {
//            queryUserCardSuccess(data);
//        } else {
        presenter.queryUserCard("3");
//        }


    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected BasePresenter[] initPresenters() {
        return new BasePresenter[]{presenter};
    }

    private void init() {
        origin = getIntent().getStringExtra("type");
        access_token = ACache.get(this).getAsString("access_token");
    }

    private void initViewPager() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarDarkFont(false, 0f)
                .statusBarColor(R.color.color_2184FA).init();

        cardAdapter = new CitizenCardvpAdatper(this, null,errormsg);
        vp_cardList.setAdapter(cardAdapter);

        vp_cardList.setPageMargin(40);
        vp_cardList.setOffscreenPageLimit(20);
        zi_cardListIndicator.setViewPager(vp_cardList);
        vp_cardList.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
                updataContent(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        cardAdapter.setChangeNickNameClickListener((position, dataBean) -> {
            //修改昵称
            List<QueryUserCardRes.DataBean.CardDetailInfolistBean> cardDetailInfolistBeanList = dataBean.getCardDetailInfolist();
            QueryUserCardRes.DataBean.CardDetailInfolistBean bean = cardDetailInfolistBeanList.get(0);
            Intent intent = new Intent(CitizenCardActivity.this, ModifyCardNickNameActivity.class);
            intent.putExtra("cardNo", dataBean.getBindCardNo());
            intent.putExtra("cardNickName", bean.getCardNickName());
            startActivityForResult(intent, CHANGE_NICKNAME_REQUEST_CODE);
        });

        adapter = new ContentAdapter(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setAutoMeasureEnabled(true);
        rv_recyclerview.setLayoutManager(linearLayoutManager);
        rv_recyclerview.setAdapter(adapter);

        initAdapterListener();

        rv_recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    List<QueryUserCardRes.DataBean> data = new ArrayList<>();
    @Override
    public void queryUserCardSuccess(QueryUserCardRes response) {
        dismissLoadingDialog();
        data = response.getData();


        if(response.getData() == null || response.getData().isEmpty()){
            Bundle bundle = new Bundle();
            bundle.putString("key", "home");
            JumpUtils.jumptoNatvie(this, "addnewcard", 0, bundle);
            finish();
        }else{
            cardAdapter.setData(response.getData());

            //根据 用户选择的卡号  进行强制选择
            QueryUserCardRes.DataBean choiseBean = (QueryUserCardRes.DataBean) getIntent().getSerializableExtra("cardData");
            for(int i=0;i<response.getData().size();i++){
                QueryUserCardRes.DataBean temp = response.getData().get(i);
                if(choiseBean.getBindCardNo().equals(temp.getBindCardNo())){
                    vp_cardList.setCurrentItem(i);
                    currentPosition = i;
                    zi_cardListIndicator.onPageSelected(i);
                    zi_cardListIndicator.notifyView();
                    updataContent(i);
                    break;
                }
            }



        }
    }


    //更新 viewpager 下面的数据 包括滑动后
    private void updataContent(int position) {
        presenter.queryYCX(data.get(position).getCardNo());
        adapter.setData(data.get(position));
        adapter.notifyDataSetChanged();
    }

    @Override
    public void queryUserCardFalie(String msg) {
        dismissLoadingDialog();

        Log.i("warningMsginfo",msg);
    }

    @Override
    public void unBindCardSucc() {
        dismissLoadingDialog();
        //移除数据
        this.data.remove(currentPosition);
        cardAdapter.removeItem(currentPosition);

        if (this.data.size() == 0) {
            finish();
            return;
        }

        //移除viewpager下面的指示器
        zi_cardListIndicator.removeViewAt(currentPosition);

        if (this.data.size() > 0 && currentPosition == this.data.size()) {
            currentPosition = currentPosition - 1;
        }

        zi_cardListIndicator.onPageSelected(currentPosition);

        updataContent(currentPosition);
    }

    @Override
    public void unBindCardFail(String msg) {
        dismissLoadingDialog();
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void queryYCXSucc(BaseBean yxcRes) {
        dismissLoadingDialog();
        money=yxcRes.getMoney();
        if (yxcRes.getMoney()==0||yxcRes.getMoney()==null)
            adapter.setYscMoney(0);
        else
            adapter.setYscMoney(money);
        Log.e("yscInfo",money+"");

        adapter.notifyDataSetChanged();
    }

    @Override
    public void queryYCXFail() {

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CHANGE_NICKNAME_REQUEST_CODE) {
                cardAdapter.refreshCardView(currentPosition, data.getStringExtra("cardNickName"));
            }
        }
    }

    public void onClick(View v){
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.tv_transactionRecord) {//交易记录
            Bundle bundle1 = new Bundle();
            String cardNo = data.get(currentPosition).getBindCardNo();
            bundle1.putString("cardNo", cardNo);
            JumpUtils.jumptoNatvie(this, "trans", 0, bundle1);
        }
    }

    //初始化adapter 监听
    private void initAdapterListener() {
        adapter.setOnTopClick(new ContentAdapter.OnTopClick() {
            @Override
            public void onCard_recharge() {
                //立即充值
                Bundle bundle = new Bundle();
                bundle.putString("url", Constant.BASE_URL + "app-front-end/#/charge/main?cardNo=" +
                        data.get(currentPosition).getBindCardNo() + "&access_token=" + access_token);
                JumpUtils.jumptoNatvie(CitizenCardActivity.this, "webView", 0, bundle);
            }

            @Override
            public void onChangePwd_qfk() {
                //修改密码 文化账户  企服卡  是一样的密码
                Bundle bundle3 = new Bundle();
                bundle3.putString("cardNo",  data.get(currentPosition).getBindCardNo());
                JumpUtils.jumptoNatvie(CitizenCardActivity.this, "specialpsd", 0, bundle3);
            }

            @Override
            public void onFootprint_rl() {
                //游玩足迹
                Bundle bundle4 = new Bundle();
                bundle4.putString("url", Constant.BASE_URL + "app-front-end/#/card/footPrint?access_token=" +
                        access_token + "&cardNo=" +  data.get(currentPosition).getBindCardNo() + "&isMain=1");
                JumpUtils.jumptoNatvie(CitizenCardActivity.this, "webView", 0, bundle4);
            }

            @Override
            public void onCard_speci_tv() {
                //去认证
                Bundle bundle2 = new Bundle();
                bundle2.putString("cardNo",  data.get(currentPosition).getBindCardNo());
                JumpUtils.jumptoNatvie(CitizenCardActivity.this, "SpecialAuthActivity", 0, bundle2);
            }

            @Override
            public void onDzcksj_tv() {
                //可用商家
                //电子钱包  可用商家跳转
                JumpUtils.jump(CitizenCardActivity.this, "business", 0);
            }

            @Override
            public void onDgkkysj_tv() {
                //可用商家
                //蛋糕卡  可用商家跳转
                Bundle bundle6 = new Bundle();
                //id 为 7 跳转下个界面  全部商家的id  7 == 蛋糕卡
                bundle6.putInt("type_id",7);
                //蛋糕卡 消费商家
                JumpUtils.jumptoNatvie(CitizenCardActivity.this, "business", 0,bundle6);
            }

            @Override
            public void onDgk_recharge() {
                //蛋糕卡 充值
                String url1 =   Constant.BASE_URL +"app-front-end/#/cakeCard/recharge?cardNo="+
                        data.get(currentPosition).getBindCardNo() + "&access_token=" + access_token ;
                Bundle bundle = new Bundle();
                bundle.putString("url", url1);
                JumpUtils.jumptoNatvie(CitizenCardActivity.this, "webView", 1, bundle);
            }

            @Override
            public void accountDetail() {
                Bundle bundle = new Bundle();
                Log.i("accountDetail",Constant.BASE_URL+"charge/account?cardNo="+data.get
                        (currentPosition).getCardNo());
                bundle.putString("url",Constant.BASE_URL+"app-front-end/#/charge/account?cardNo="+data.get
                        (currentPosition).getCardNo()+ "&access_token=" + access_token);
                JumpUtils.jumptoNatvie(CitizenCardActivity.this, "webView", 1, bundle);
            }

            @Override
            public void kysj_cake() {
                //可用商家
                //蛋糕卡  可用商家跳转
                Bundle bundle6 = new Bundle();
                //id 为 7 跳转下个界面  全部商家的id  7 == 蛋糕卡
                bundle6.putInt("type_id",7);
                //蛋糕卡 消费商家
                JumpUtils.jumptoNatvie(CitizenCardActivity.this, "business", 0,bundle6);
            }
        });

        adapter.setOnBottomClick(new ContentAdapter.OnBottomClick() {
            @Override
            public void onBtnDelCard() {
                final TwoButtonDialog dialog = new TwoButtonDialog(CitizenCardActivity.this,
                        "确认删除卡片么？");
                dialog.setOnOkClickListener(new TwoButtonDialog.OnOkClickListener() {
                    @Override
                    public void onOkClick() {
                        dialog.cancel();
                    }
                });
                dialog.setOnCancelClickListener(new TwoButtonDialog.OnCancelClickListener() {
                    @Override
                    public void onCancelClick() {
                        showLoadingDialog();
                        presenter.unBindCard(access_token,  data.get(currentPosition).getBindCardNo());
                    }
                });
                dialog.show();
            }
        });

    }
}